package middleware

import (
	"fmt"
	"restaurant-system/pkg/utils"
	"strings"

	"github.com/gin-gonic/gin"
)

func AuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		authHeader := c.GetHeader("Authorization")
		fmt.Printf("Auth Header: %s\n", authHeader)

		if authHeader == "" {
			c.JSON(401, gin.H{"error": "未登录"})
			c.Abort()
			return
		}

		parts := strings.Split(authHeader, " ")
		fmt.Printf("Auth parts: %v\n", parts)

		if len(parts) != 2 || parts[0] != "Bearer" {
			c.JSON(401, gin.H{"error": "无效的认证格式"})
			c.Abort()
			return
		}

		tokenString := parts[1]
		fmt.Printf("Token string: %s\n", tokenString)

		claims, err := utils.ValidateToken(tokenString)
		if err != nil {
			fmt.Printf("Token validation error: %v\n", err)
			c.JSON(401, gin.H{"error": "无效的 token"})
			c.Abort()
			return
		}

		fmt.Printf("Valid token for user ID: %d\n", claims.UserID)
		c.Set("userID", claims.UserID)
		c.Next()
	}
}
